package com.yass.zaika;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class RecipeForm extends Activity{

	private TextView recipe_description;
	private Zaika application;
	private TextView recipe_title;
	private int result_index;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.recipedisplay);
		initializeVariables();
		setForm();
	}

	public void initializeVariables(){
		recipe_description = (TextView)findViewById(R.id.recipe_description);
		recipe_title = (TextView)findViewById(R.id.recipe_title);
		application = (Zaika)getApplication();
		
		recipe_description.setMovementMethod(ScrollingMovementMethod.getInstance());
	}
	
	public void setForm()
	{
		Intent intent = getIntent();
		result_index = Integer.parseInt(intent.getStringExtra("buttonId"));
		recipe_title.setText(application.getDisplay().getResult(result_index).getRecipeName());
		recipe_description.setText(application.getDisplay().getResult(result_index).getRecipe());
		
	}
	
	public void saveRecipe() 
	{
		
		final String recipe_name = recipe_title.getText() +"\n";
		final String recipe = recipe_description.getText() +"\n";
		
		File folder = getDir("Cookbook", Context.MODE_WORLD_WRITEABLE);
		final String FILENAME = folder.getAbsolutePath()+"/"+recipe_title.getText();
		
		File file = new File(FILENAME);
		
		
		
		try {
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(recipe_name.getBytes());
			fos.write(recipe.getBytes());
			fos.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Toast.makeText(getApplicationContext(), "Error in creating or writing to file",Toast.LENGTH_LONG);
			
		}
	
		if(file.exists())
			Toast.makeText(getApplicationContext(), "Saving complete", Toast.LENGTH_LONG).show();
			
		else
			Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();

		
		
	}
	public void buttonClick(View v){
		
		switch(v.getId()){
		
		case(R.id.save_cookbook):{
			saveRecipe();
			break;
			
		}
		
		}
		
	}
}
